<?php
/*
 * ebiz front
 *
 * PostController
 *
 * @author allen
 *
 */
require_once '../app/core/controllers/BaseController.php';
require_once '../app/services/CustomerService.php';
require_once '../app/views/UtilityView.php';
require_once '../app/core/utils/HttpUtil.class.php';
require_once '../app/controllers/UtilityController.php';
$path = "../$GLOBALS[local]/"."utility.php";
require_once $path;//get the internationalization file path to set the value in param

require_once '../app/services/CategoryService.php';
require_once '../app/services/ProductService.php';

require_once '../app/services/ShoppingCartService.php';
require_once '../app/services/AAService.php';
require_once '../app/services/OrderService.php';
require_once '../app/services/ShippingFeeService.php';
require_once '../app/services/UserInfoService.php';
require_once '../app/services/AgentAccountService.php';
require_once '../app/services/SystemLogService.php';
require_once '../app/services/PaymentService.php';
require_once '../app/services/QueryService.php';
require_once '../app/services/ApplyGiftService.php';
require_once '../app/services/EmailService.php';

require_once '../app/constants/ConfigConstants.php';

require_once '../app/component/MailUtil.php';
require_once '../app/views/UtilityView.php';
require_once '../app/component/Number.php';

class PostController extends BaseController
{
    public function register(){     //do not have  validate
		require_once "../". $GLOBALS["local"] ."/"."utility.php";
//    	$quickpage = strtolower(HttpUtil::getPostString('quickpage'));//快速注册页面注册后进入checkout页面
    	$name = strtolower(HttpUtil::getPostString('username'));
		$email = strtolower(HttpUtil::getPostString('email'));
		$password = md5(HttpUtil::getPostString('password'));

		$isSchool = HttpUtil::getPostString('isSchool');
		if($isSchool == 1){
			$campusesId = HttpUtil::getPostString('campusesId');
		}
		$customerNumber = Number::getCustomerNumber();
		$ip=$_SERVER["REMOTE_ADDR"];
        $customerService = new CustomerService();
        if ($customerService->validateEmail($email)){   //true is the user can register
        	if($isSchool == 1){
        		$param = array($customerNumber, $name, $email, $password, $ip, $campusesId);
        	} else {
        	    $param = array($customerNumber, $name, $email, $password, $ip);
        	}
	        $activate_key = $customerService->addUser($param);
	        $activation = base64_decode($activate_key);
	        $paramActivateKey = explode('-', $activation);
	        $userId = $paramActivateKey[0];
	        $userPointService = new UserPointService();
            $userPointService->updatePoint($userId, 0, 1);
	        //send email to active user//cancel at 0922
	        $emailTitle = ACTIVEEMAILTITLE;
	        $link = "<a href='"."http://".ConfigConstants::$domainPath."/u/activation?uid=".$activate_key."'>"."http://".ConfigConstants::$domainPath."/u/activation?uid=".$activate_key."</a>";
	        $emailParam = array("name" => $name, "link" => $link, "email" => $email);
	        
            $emailService = new EmailService();
            $emailTitle = ACTIVEEMAILTITLE;//邮件title
            $emailBodyToUser = $emailService->activeEmailView($emailParam);//获得邮件主体内容
            MailUtil::sendMail($email, $emailTitle, $emailBodyToUser);
	        
//	        session_destroy();
//            if( empty($quickpage) ){
            	header("Location: http://".ConfigConstants::$domainPath."/u/registersuccess");
//            }else{
//            	header("Location: http://".ConfigConstants::$domainPath."/u/checkout");
//            }
	        
	        exit();
        }else{     //email has exist
	        header("Location: http://".ConfigConstants::$domainPath."/u/register");
        }
    }

    public function findpassword(){     //the url  must lowercase
        $email = strtolower(HttpUtil::getPostString('email'));
        $customerService = new CustomerService();
        $result = $customerService->getPassword($email);
//        send email to update the password
        $emailTitle = FINDPWDEMAILTITLE;
        $name = $result[2];
        $link = "<a href='http://".ConfigConstants::$domainPath."/u/updatePassword?getPasswordKey=".$result[0]."'>"."http://".ConfigConstants::$domainPath."/u/updatePassword?getPasswordKey=".$result[0]."</a>";
        $emailParam = array("name" => $name, "link" => $link);
        $utilityView = new UtilityView();
        $emailBody = $utilityView->render("findPasswordEmailView", $emailParam);
        MailUtil::sendMail($email, $emailTitle, $emailBody);
        header("Location: http://".ConfigConstants::$domainPath."/u/findpasswordsuccess");
//        echo "<a href='/u/updatePassword?getPasswordKey=".$result[0]."'>update password</a>";
    }

    public function updatepassword(){
    	$getPasswordKey = HttpUtil::getPostString('getPasswordKey');
    	$newPassword = md5(HttpUtil::getPostString('password'));
    	$param = explode('-' ,base64_decode($getPasswordKey));
    	$id = $param[0];
    	$customerService = new CustomerService();
    	$result = $customerService->updatePassword($id, $getPasswordKey, $newPassword);
    	if($result){
    		echo "Your password update is success!";
    	}else{
    		echo "Your password is already updated!";
    	}
    	header("Location: http://".ConfigConstants::$domainPath."/u/updatepasswordsuccess");
    //	echo "<a href='http://".ConfigConstants::$domainPath."/'>Click here to go home page.</a>";
    }

    //select page
    public function select(){
    	$path = "";    //not used , used in  used in select of utilitycontroller
    	$email = "";
    	if(strtolower(HttpUtil::getPostString('emails')) != ""){
			$email = strtolower(HttpUtil::getPostString('emails'));
        }else{
        	$email = strtolower(HttpUtil::getPostString('emailF'));
        }
        $param = array('email'=>$email);
    	$password = HttpUtil::getPostString('passwords');
    	$r = HttpUtil::getPostString('r');
        $view = new UtilityView();
    	if($r == 'r1'){    //if email do not have then goto the register page, or else goto the full page
    		$customerService = new CustomerService();
    		$result = $customerService->validateEmail($email);
    		if(!$result){     //the email already exist
    			$param = array('email'=>$email, 'unique'=> EMAILUNIQUE);
		        echo $view->render("getFullView", $param); 	//goto full page
    		}else{    //the email do not have
    			echo $view->render("getRegisterView", $param, $path);
    		}
    	}elseif($r == 'r2'){   //goto login function
    		$customerService = new CustomerService();
            $result = $customerService->validateEmail($email);  //if email not exist=>true
            if($result){     //the email do not have and login error
                $utilityController = new UtilityController();
                $param = array('email'=>$email, 'error'=>LOGINERROR);
                $utilityController->full($param);  //from controller show the full view
            }else{    //the email exist
	            if(!isset($_SESSION['num'])){
		        	$_SESSION['num'] = 1;  //controll the login number
		        }else{
		        	$_SESSION['num']++;
		        }
		        $password = md5(HttpUtil::getPostString('passwords'));
		        $param = array($email, $password);
		        $customerService = new CustomerService();
		        $status = $customerService->getByEmailAndPassword($param);
		    	switch ($status){
		            case -1:
		            	$view = new UtilityView();
		            	$param = array("email"=>$email);
		            	echo $view->render("getLoginView", $param);
		                break;
		    		case 1: //the first location is login function to set the session
		    			unset($_SESSION['num']);
		    			//set the customer id , if login success
		                $result = $customerService->getCustomerInfoByEmailAndPassword($param);
            			$customerId = $result[0]['id'];
            			AAService::setCustomer($customerId);
                        $customerService->updateLastLoginById($customerId);
                        $shoppingCartService = new ShoppingcartService();
                        $shoppingCartService->combineShoppingCart($customerId); //if login combine cookie info to DB
		                //set the https protocol save in cookie
		                $token = md5(uniqid(mt_rand(),true));
//		                setcookie("token", $token, time() + 60*30, '/', ".".DOMAIN, true); //set the time is 30 minute
		                setcookie("token", $token, time() + 60*30, '/', ".".DOMAIN, false); //false is used in testing environment
		                $_SESSION['token'] = $token;
		                $url = isset($_COOKIE["url"]) ? $_COOKIE["url"] : "/";
		                setcookie("url", "", time() - 3600*24, '/');
                        header("Location: $url");
//                        header('Cache-control: private, must-revalidate');
//            			echo "<script language='javascript'>history.go(-2);</script>";
		                exit();
		                break;
		    	}
            }
    	}else{     //goto forget password page
    		self::findPassword();
    	}
    }

    public function logout(){
    	session_destroy();
    	header("Location: http://".ConfigConstants::$domainPath."/");
    	exit();
    }

//    public function showMenu(){    //ajax use in front.js , show the menu in headerView
//        $category = new CategoryService();
//        $parentId = "0";
//        $result = $category->createTree($parentId);
//        $result = array('result' => $result);
//        echo json_encode($result);
//    }

    public function showproductinfo(){  //ajax use in front.js , show the product info in productView
        $urlTitle = strtolower(HttpUtil::getPostString("urlTitle"));
        $productService = new ProductService();
        $productInfo = array();
        $productInfo = $productService->getProductByUrlTitle($urlTitle);
        $result = array('result' => $productInfo);
        echo json_encode($result);
    }

    public function deleteshoppinginfo(){   //used in shopping cart to delete the shopping cart item info
    	$scId = HttpUtil::getGetString("scId");
    	$scId = intval($scId);
    	if($scId == 0){
    		$scId =1;
    	}
    	$shoppingcartService = new ShoppingcartService();
    	$shoppingcartService->deleteShoppingCartInfo($scId);
    	header("Location: http://".ConfigConstants::$domainPath.'/u/cart');
    	exit();
    }

    public function updateshoppingcart(){
    	if(AAService::isLogin()){
    		self::updateDBShoppingInfo();
    	}else{
    		self::updateCookieShoppingInfo();
    	}
    }

    public function addtoshoppingcart(){    //used in product View
    	$productItemId = HttpUtil::getPostString("hProductItemId");
    	$quantity = 1;
    	$salePrice = HttpUtil::getPostString("hSalePrice");
    	$productId = HttpUtil::getPostString("hProductId");
    	$shoppingCartService = new ShoppingcartService();
        if(AAService::isLogin()){  //if user already login
        	$customerId = AAService::getCustomer();  //get user id
            $param = array($productId, $productItemId, $customerId, $quantity, $salePrice);
            if($shoppingCartService->shoppingCartIsExist($productItemId, $customerId)){ //this item is exist , only update the quantity
            	$shoppingCartService->addQuantityByCidItemid($customerId, $productItemId, $quantity);
            }else{  //this item is not exist , add a new one
            	$shoppingCartService->addShoppingCart($param);  //insert into value to shopping_carts table
            }
            
            
        }else{  //user not login , set the shopping cart to cookie
            $param = array("productItemId"=>$productItemId, "quantity"=>$quantity, "salePrice"=>$salePrice);
//            var_dump($param);die;
            $shoppingCartService->saveToCookie($param);
        }
		header("Location: http://".ConfigConstants::$domainPath.'/u/cart');
		exit();
    }

    public function deletecookieshoppinginfo(){
        $pItemId = HttpUtil::getGetString("pItemId");
        if(!empty($_COOKIE['cart'])){
            foreach ($_COOKIE['cart'] as $key => $value) {
            	if($key == $pItemId){
            		setcookie("cart[$key][quantity]", "", time() - 3600*24, '/');
                    setcookie("cart[$key][salePrice]", "", time() - 3600*24, '/');
            	}
            }
        }
        header("Location: http://".ConfigConstants::$domainPath.'/u/cart');
        exit();
    }

    public function updatedbshoppinginfo(){
        $shoppingCartService = new ShoppingcartService();
        $quantityArray = HttpUtil::getPostValue("quantity");
        $itemIdArray = HttpUtil::getPostValue("itemId");
        $scIdArray = HttpUtil::getPostValue("scId");
        $customerId = AAService::getCustomer();
        for($i = 0; $i < count($itemIdArray); $i++){
        	if($quantityArray[$i] <= 0){
//        		$quantityArray[$i] = 1;
                $shoppingCartService->deleteShoppingCartInfo($scIdArray[$i]);
        		header("Location: http://".ConfigConstants::$domainPath.'/u/cart');
        	}
        	$shoppingCartService->updateQuantityByItemid($customerId, $itemIdArray[$i], $quantityArray[$i]);
        }
        header("Location: http://".ConfigConstants::$domainPath."/u/cart");
        exit();
    }

    public function updatecookieshoppinginfo(){
        $quantityArray = HttpUtil::getPostValue("quantity");
        $itemIdArray = HttpUtil::getPostValue("itemId");
        for($i = 0; $i < count($itemIdArray); $i++){
            if($quantityArray[$i] <= 0){    //if user set the quantity is 0 or negative , then set the default value '1'
                $quantityArray[$i] = 1;
            }else if(!is_numeric($quantityArray[$i])){
            	$quantityArray[$i] = 1;
            }else{//if number have decimal fraction then transform integer
                $quantityArray[$i] = intval($quantityArray[$i]);
            }
            if(!empty($_COOKIE['cart'])){
                foreach ($_COOKIE['cart'] as $key => $value) {
                    if($key == $itemIdArray[$i]){
                        setcookie("cart[$key][quantity]", $quantityArray[$i], time() + 3600*24, '/');
                    }
                }
            }
        }
        header("Location: http://".ConfigConstants::$domainPath."/u/cart");
        exit();
    }

    /**
     * use in shoppingCart View to submit of from,the info to show in checkout View
     */
    public function updateshoppingforcheckout(){
        if(AAService::isLogin() && AAService::isValidateForHttps()){
	        $shoppingCartService = new ShoppingcartService();
	        $quantityArray = HttpUtil::getPostValue("quantity");
	        $itemIdArray = HttpUtil::getPostValue("itemId");
	        $salePriceArray = HttpUtil::getPostValue("salePrice");
	        $scIdArray = HttpUtil::getPostValue("scId");
	        $customerId = AAService::getCustomer();
	        $shoppingCartService->updateStateForClearById($customerId);
	        for($i = 0; $i < count($itemIdArray); $i++){
//	            if($quantityArray[$i] <= 0 || $salePriceArray[$i] <= 0){    //if user set the quantity is 0 , then set the default value '1'
	            if($quantityArray[$i] <= 0){    //if user set the quantity is 0 , then set the default value '1'
	                $quantityArray[$i] = 1;
	            }
	            if($salePriceArray[$i] <= 0){
	            	$shoppingCartService->deleteShoppingCartInfo($scIdArray[$i]);
	            }
	            //update the status of shoppingCart table //if qty more than inventory then set qty == inventory
	            $shoppingCartService->updateStateById($customerId, $itemIdArray[$i], $quantityArray[$i]);
	        }
	        header("Location: ".$GLOBALS["SSLProtocol"]."://".ConfigConstants::$domainPath."/u/checkout");
	        exit();
        }else{
            $url = $GLOBALS["SSLProtocol"] . "://".ConfigConstants::$domainPath. "/u/checkout";
            setcookie("url", $url, time() + 3600*24, '/');
//        	echo "<script language='javascript'>window.location='http://www.zhousl.com/'</script>";
            header("Location: ".$GLOBALS["SSLProtocol"]."://".ConfigConstants::$domainPath."/u/select");
            exit();
        }
    }

    /**
     * use in checkout page to place order
     *
     */
    public function placeorder(){
    	if( AAService::isLogin( true ) ) {
    	
	    	$address = HttpUtil::getPostString("address");
	    	$deliveryRadio = HttpUtil::getPostString("deliveryRadio");
	    	$deliveryDate = HttpUtil::getPostString("deliveryDate");
	    	$radioPay = HttpUtil::getPostString("radioPay");
	    	$allTotal = HttpUtil::getPostString("allTotal");
	    	if( empty($address) || empty($deliveryRadio) || empty($deliveryDate) || empty($radioPay) || $allTotal <= 0 ){
	    		header("Location: ".$GLOBALS["SSLProtocol"]."://".ConfigConstants::$domainPath."/u/checkout");
	            exit();
	    	}
	        $orderService = new OrderService();
	        //judge the user bought quantity if less than inventity of DB
	//        $itemIdArray = HttpUtil::getPostValue("itemId"); //id is array!
	//        $quantityArray = HttpUtil::getPostValue("quantity");
	//        $itemIds = implode(",", $itemIdArray);
	//        $isCanBuyGood = $orderService->isCanBuyGood($itemIds, $quantityArray);
	//        if(!$isCanBuyGood){
	//            header("Location: ".$GLOBALS["SSLProtocol"]."://".ConfigConstants::$domainPath."/u/checkout");
	//            exit();
	//        }
	        $orderId = $orderService->placeOrder();
	        if(!$orderId){ //if do not have id or return false then go to checkout page
	            header("Location: ".$GLOBALS["SSLProtocol"]."://".ConfigConstants::$domainPath."/u/checkout");
	            exit();
	        }
	        $orderId = base64_encode($orderId);
	        header("Location: http://".ConfigConstants::$domainPath."/u/successorder?orderId=$orderId");
	        exit();
    	}
        
    }



//////////////////////////////////////////////////////////////////////////////////////////////////////

    public function modifypassword(){
    //	require_once "../". $GLOBALS["local"] ."/"."utility.php";
        AAService::isLogin(true);
    	$oldPassword = md5(HttpUtil::getPostString('oldPassword'));
    	$customerService = new CustomerService();

    	$AAService = new AAService();
    	$customerId = $AAService->getCustomer();
    	$newPassword = HttpUtil::getPostString('newPassword');
    	$rePassword = HttpUtil::getPostString('repassword');
    	if($customerService->validateOldPassword($oldPassword,$customerId) && $newPassword==$rePassword){
    		$param = array(md5($newPassword), $customerId);

    		$customerService->updateCustomer($param);
    		header("Location: http://".ConfigConstants::$domainPath."/userinfo/index");
    		exit();
    	} else{
    		header("Location: http://".ConfigConstants::$domainPath."/userinfo/modifypassword");
    	}

    }

/**
 * Add and Edit delivery Submit
 */
    public function delivery(){
    	AAService::isLogin(true);
    	$deliveryId = HttpUtil::getPostString('deliveryId');
    	$receiverName = HttpUtil::getPostString('receiverName');
    	$provinceId = HttpUtil::getPostString('province');
    	$cityId = HttpUtil::getPostString('city');
    	$countyId = HttpUtil::getPostString('county');
    	$detailAddress = HttpUtil::getPostString('detailAddress');
    	$telephone = HttpUtil::getPostString('phone');
    	$mobile = HttpUtil::getPostString('mobile');
    	$email = HttpUtil::getPostString('email');
    	if($receiverName && $provinceId && $cityId && $countyId && $detailAddress && $mobile && $email){
    		$userInfoService = new UserInfoService();
    		if($deliveryId && $deliveryId>0){
    			$param = array($receiverName, $provinceId,$cityId,$countyId,$detailAddress,$telephone,$mobile,$email,$deliveryId);
    		    $userInfoService = new UserInfoService();
    		    $userInfoService->updateDelivery($param);
    		} else {
    		    $userId = AAService::getCustomer();
    		    $param = array($userId,$receiverName, $provinceId,$cityId,$countyId,$detailAddress,$telephone,$mobile,$email);
    		    $deliveryId = $userInfoService->saveDelivery($param);
    		}

    	}

    	header("Location: http://".ConfigConstants::$domainPath."/userinfo/delivery");
    	exit();

    }



    /**
     * Run it if somebody send campus angent apply
     * @author by M.Wang
     * @desc 2009-09-01
     */
    public function campusapply(){
    	AAService::isLogin(true);
    	if(!AAService::isActive()){
    		header("Location: /userinfo/index");
    	    exit();
    	}
    	$param = array();
    	/**
    	 * get post data
    	 */
    	$username = trim( strtolower( HttpUtil::getPostString('username') ) );
		$param['full_name'] = trim( HttpUtil::getPostString('full_name') );
		$param['email'] = trim( HttpUtil::getPostString('email') );
		$param['age'] = trim( HttpUtil::getPostString('age') );
		$param['sex'] = trim( HttpUtil::getPostString('sex') );
		$param['school'] = trim( HttpUtil::getPostString('school') );
		$param['department'] = trim( HttpUtil::getPostString('department') );
		$param['zhuanye'] = trim( HttpUtil::getPostString('zhuanye') );
		$param['student_id'] = trim( HttpUtil::getPostString('student_id') );
		$param['tel'] = trim( HttpUtil::getPostString('tel') );
		$param['mobile'] = trim( HttpUtil::getPostString('mobile') );
		$param['address'] = trim( HttpUtil::getPostString('address') );
		$param['dormitory_address'] = trim( HttpUtil::getPostString('dormitory_address') );
		$param['remarks'] = trim( HttpUtil::getPostString('remarks') );
		$param['evaluation'] = trim( HttpUtil::getPostString('evaluation') );
		$param['qq'] = trim( HttpUtil::getPostString('qq') );
        $param['postal_code'] = trim( HttpUtil::getPostString('postal_code') );
        $param['dentity_id'] = trim( HttpUtil::getPostString('dentity_id') );
        $param['address_1'] = trim( HttpUtil::getPostString('province') );
        $param['address_2'] = trim( HttpUtil::getPostString('city') );
        $param['address_3'] = trim( HttpUtil::getPostString('county') );
        $customerService = new CustomerService();
        $result = $customerService->validateUserName($username, true);
        $param['user_id'] = $result['id'];//get user id

    	/**
    	 * save into `apply_school_actings`
    	 */
        require_once "../". $GLOBALS["local"] ."/"."utility.php";
        $customerService = new CustomerService();
        if( $customerService->addAgent( $param ) )
        	$message = ADDAGENTFINISHED;
        else
        	$message = ADDAGENTFAILED;
        require_once '../app/views/MessageView.php';
        exit;

    }

    public function updateaddress(){
    	AAService::isLogin(true);
    	$teamName = HttpUtil::getPostString('teamName');
    	$fullName = HttpUtil::getPostString('fullName');
    	$province = HttpUtil::getPostString('province');
    	$city = HttpUtil::getPostString('city');
    	$addr = HttpUtil::getPostString('receiveAddr');
    	$zip = HttpUtil::getPostString('zipCode');
    	$mobile = HttpUtil::getPostString('mobile');
    	$phone = HttpUtil::getPostString('fixedPhone');
    	$userId = AAService::getCustomer();
        if($teamName && $fullName && $province && $city && $addr && $zip && $mobile){

    		$param = array($teamName,$fullName, $province,$city,$addr,$zip,$mobile,$phone,$userId);
    	//	print_r($param);exit;
    		$userInfoService = new UserInfoService();
    		$userInfoService->updateAddress($param);
    	//	header("Location: http://".ConfigConstants::$domainPath."/");
    	}
    	header("Location: http://".ConfigConstants::$domainPath."/userinfo/updateaddress");
    	exit();
    }

    public function submitsupplement(){
    	AAService::isLogin(true);
    	$choose = trim(HttpUtil::getPostString('choose'));
    	$price = trim(HttpUtil::getPostString('price'));
    	$ptype = '';
        $userId = AAService::getCustomer();
        $logService = new SystemLogService();
        $paymentService = new PaymentService();
        $agentAccountSercive = new AgentAccountSercive();
        $accountAgentTotal = $agentAccountSercive->getAccountAgentTotalByUserId($userId);
        $data = array();
        $data['user_id'] = $userId;
        $data['trade_type'] = 1;
        $data['trade_sum'] = $price;
        $data['create_id'] = $_SESSION['username'];
        $data['modify_id'] = $_SESSION['username'];
        $data['modified'] =date("Y-m-d H:i:s");
        $data['created'] =date("Y-m-d H:i:s");
        $data['balance_prev']=$accountAgentTotal['balance'];
        $data['debt_prev']=$accountAgentTotal['debt_balance'];
        $data['freeze_prev']=$accountAgentTotal['freezed_balance'];
        $data['usage_balance_prev']=$accountAgentTotal['usage_balance'];
        $data['balance_now']=$accountAgentTotal['balance'];
        $data['debt_now']=$accountAgentTotal['debt_balance'];
        $data['freeze_now']=$accountAgentTotal['freezed_balance'];
        $data['usage_balance_now']=$accountAgentTotal['usage_balance'];

    	if($choose == 1){
    		$data['out_id'] = trim(HttpUtil::getPostString('account'));
    		$data['supplement_type'] = trim(HttpUtil::getPostString('paymenttype'));
    		$data['trade_operator'] = $_SESSION['username'];
    		$data['status'] = 2;
    		$ptype = 'OS';
    	}else if($choose == 2){
    		$data['out_id'] = trim(HttpUtil::getPostString('tranaccount'));
            $data['supplement_type'] = trim(HttpUtil::getPostString('bank'));
            $data['trade_operator'] = $_SESSION['username'];
            $data['status'] = 6;
            $data['trade_num'] = trim(HttpUtil::getPostString('trannum'));
            $data['out_name'] = trim(HttpUtil::getPostString('tranname'));
            $data['in_id'] = trim(HttpUtil::getPostString('akaccount'));
            $data['out_date'] = HttpUtil::getPostString('trantime').' '.HttpUtil::getPostString('fhour').':'.HttpUtil::getPostString('fmin');
            $ptype = 'OFS';
    	}

    	$id = $agentAccountSercive->saveAccountAgentTradeLog($data);
    	$sn = Number::getTradeLogSN($id,$data['trade_type']);
    	$agentAccountSercive->updateSN(array("sn"=>$sn),$id);
        $logService->insertSystemLog($ptype,$_SESSION['username'],1,$data);
        if($choose==1){
            $link = $paymentService->alipayPayment($price,$sn);
            echo '<script> window.location="'.$link.'"</script>';
        }else{
            header("Location: http://".ConfigConstants::$domainPath."/trade/supplementlogs");
        }
        exit;
    }


    public function submitwithdraw(){
    	AAService::isLogin(true);
    	$choose = trim(HttpUtil::getPostString('choose'));
        $price = trim(HttpUtil::getPostString('price'));
        $logService = new SystemLogService();
    	$agentAccountSercive = new AgentAccountSercive();
    	$userId = AAService::getCustomer();
    	$data = array();
        $data['user_id'] = $userId;
        $data['trade_type'] = 3;
        $data['trade_sum'] = $price;
        $data['create_id'] = $_SESSION['username'];
        $data['modify_id'] = $_SESSION['username'];
        $data['status'] = 6;
        $data['modified'] =date("Y-m-d H:i:s");
        $data['created'] =date("Y-m-d H:i:s");
        $data['in_id'] = HttpUtil::getPostString('account');
        if($choose == 1){
            $data['withdraw_type'] = HttpUtil::getPostString('paymenttype');
            $receivetype="OLWD";
        }elseif($choose == 2){
            $data['withdraw_type'] = HttpUtil::getPostString('bank');
            $data['in_name'] = trim(HttpUtil::getPostString('tranname'));
            $data['in_bank_name'] = trim(HttpUtil::getPostString('bankname'));
            $receivetype="AOFA";
        }
        $agentData = array();
        $accountAgentTotal = $agentAccountSercive->getAccountAgentTotalByUserId($userId);
        $data['balance_prev']=$accountAgentTotal['balance'];
        $data['debt_prev']=$accountAgentTotal['debt_balance'];
        $data['freeze_prev']=$accountAgentTotal['freezed_balance'];
        $data['usage_balance_prev']=$accountAgentTotal['usage_balance'];
        $agentData['modify_id'] = $_SESSION['username'];
        $agentData['modified'] = date("Y-m-d H:i:s");

        $data['account_freeze_offset'] = $price;
        $data['account_usage_balance_offset'] = -$price;

        $agentData['usage_balance']=$accountAgentTotal['usage_balance']-$price;
        $agentData['freezed_balance']=$accountAgentTotal['freezed_balance']+$price;

        $data['balance_now']=$accountAgentTotal['balance'];
        $data['freeze_now']=$agentData['freezed_balance'];
        $data['usage_balance_now']=$agentData['usage_balance'];
        $data['debt_now']=$accountAgentTotal['debt_balance'];
        $id = $agentAccountSercive->saveAccountAgentTradeLog($data);
        $sn = Number::getTradeLogSN($id,$data['trade_type']);
        $agentAccountSercive->updateSN(array("sn"=>$sn),$id);
        $logService->insertSystemLog($receivetype,$_SESSION['username'],1,$data);
        $agentAccountSercive->updateAccountAgentTotal($agentData,$accountAgentTotal['id']);
        $logService->insertSystemLog($receivetype,$_SESSION['username'],1,$agentData,$accountAgentTotal['id']);
        header("Location: http://".ConfigConstants::$domainPath."/trade/withdrawlogs");
        exit();
    }

    /**
     * supply success action
     */
    public function supplysuccess(){
        $paymentService = new PaymentService();
        $agentAccountSercive = new AgentAccountSercive();
//        $logService = new SystemLogService();
        $verify_result = $paymentService->getPaymentResult();
        if($verify_result) {
            if(trim($_GET['trade_status']) == 'TRADE_FINISHED') {
                $payments = $agentAccountSercive->getPaymentBySN($_GET['out_trade_no']);
                if(empty($payments)){
                	header("Location: http://".ConfigConstants::$domainPath."/trade/supplementlogs");
                }
                $payment = $payments[0];
//                $userId = $payment['user_id'];
//                $agentTotal = $agentAccountSercive->getAccountAgentTotalByUserId($userId);
//                $paymentData = array();
//                $agentData = array();
//                //payment
//                $paymentData['balance_prev']=$agentTotal['balance'];
//                $paymentData['debt_prev']=$agentTotal['debt_balance'];
//                $paymentData['freeze_prev']=$agentTotal['freezed_balance'];
//                $paymentData['usage_balance_prev']=$agentTotal['usage_balance'];
//                $paymentData['modify_id']= $_SESSION['username'];
//                $paymentData['modified'] =date("Y-m-d H:i:s");
//                $paymentData['trade_num']=$_GET['trade_no'];
//                $paymentData['status'] = 3;
//                $paymentData['out_date']=date("Y-m-d H:i:s");
//                $agentData['modify_id']= $_SESSION['username'];
//                $agentData['modified'] =date("Y-m-d H:i:s");
//                $agentData['supplement_cnt']=$agentTotal['supplement_cnt']+1;
//                $agentData['supplement_sum']=$agentTotal['supplement_sum']+$payment['trade_sum'];
//                $agentData['supplement_last_time']=date("Y-m-d H:i:s");
//
//                if($agentTotal['debt_balance']<=0){
//                    $paymentData['account_balance_offset']=$payment['trade_sum'];
//                    $paymentData['account_usage_balance_offset']=$payment['trade_sum'];
//
//                    $agentData['balance']=$agentTotal['balance']+$payment['trade_sum'];
//                    $agentData['usage_balance']=$agentTotal['usage_balance']+$payment['trade_sum'];
//
//                    $paymentData['balance_now']=$agentData['balance'];
//                    $paymentData['freeze_now']=$agentTotal['freezed_balance'];
//                    $paymentData['usage_balance_now']=$agentData['usage_balance'];
//                    $paymentData['debt_now']=$agentTotal['debt_balance'];
//                }else{
//                    if($payment['trade_sum']>$agentTotal['debt_balance']){
//                        $tradesum = $payment['trade_sum']-$agentTotal['debt_balance'];
//                        $paymentData['account_balance_offset']=$tradesum;
//                        $paymentData['account_usage_balance_offset']=$tradesum;
//                        $paymentData['account_debt_balance_offset']=-$agentTotal['debt_balance'];
//
//                        $agentData['balance']=$agentTotal['balance']+$tradesum;
//                        $agentData['usage_balance']=$agentTotal['usage_balance']+$tradesum;
//                        $agentData['debt_balance'] = 0;
//
//                        $paymentData['balance_now']=$agentData['balance'];
//                        $paymentData['freeze_now']=$agentTotal['freezed_balance'];
//                        $paymentData['usage_balance_now']=$agentData['usage_balance'];
//                        $paymentData['debt_now']=$agentData['debt_balance'];
//                    }else{
//                        $tradedebt = $agentTotal['debt_balance']-$payment['trade_sum'];
//                        $paymentData['account_debt_balance_offset']=-$payment['trade_sum'];
//                        $agentData['debt_balance'] = $tradedebt;
//                        $paymentData['balance_now']=$agentTotal['balance'];
//                        $paymentData['freeze_now']=$agentTotal['freezed_balance'];
//                        $paymentData['usage_balance_now']=$agentTotal['usage_balance'];
//                        $paymentData['debt_now']=$agentData['debt_balance'];
//                    }
//
//                }
//                $agentAccountSercive->updateAccountAgentTradeLog($paymentData,$payment['id']);
//                $agentAccountSercive->updateAccountAgentTotal($agentData,$agentTotal['id']);
//                $logService->insertSystemLog('OS',$_SESSION['username'],1,$paymentData,$payment['id']);
//                $logService->insertSystemLog('OS',$_SESSION['username'],1,$agentData,$agentTotal['id']);
                header("Location: http://".ConfigConstants::$domainPath."/trade/tradeloginfo/" . $payment['id']);
                exit();
            }
        }
        header("Location: http://".ConfigConstants::$domainPath."/trade/supplementlogs");

    }

    
    public function supplychangetotal(){
        $paymentService = new PaymentService();
        $agentAccountSercive = new AgentAccountSercive();
        $logService = new SystemLogService();
        $verify_result = $paymentService->getNotifyResult();     
        $userId = 0;
        if($verify_result){         
             $tradeNo = trim($_POST['out_trade_no']);            
             $tradeStatus= trim($_POST['trade_status']);
             if($tradeStatus == 'TRADE_FINISHED') {
                $payments = $agentAccountSercive->getPaymentBySN($tradeNo);
                if(!empty($payments) && $payments[0]['status'] == 2){
                        $payment = $payments[0];
                        $userId = $payment['user_id'];
                        $agentTotal = $agentAccountSercive->getAccountAgentTotalByUserId($userId);
                        $paymentData = array();
                        $agentData = array();
                        //payment
                        $paymentData['balance_prev']=$agentTotal['balance'];
                        $paymentData['debt_prev']=$agentTotal['debt_balance'];
                        $paymentData['freeze_prev']=$agentTotal['freezed_balance'];
                        $paymentData['usage_balance_prev']=$agentTotal['usage_balance'];
                        $paymentData['modify_id']= $_SESSION['username'];
                        $paymentData['modified'] =date("Y-m-d H:i:s");
                        $paymentData['trade_num']=trim($_POST['trade_no']);
                        $paymentData['status'] = 3;
                        $paymentData['out_date']=date("Y-m-d H:i:s");
                        $agentData['modify_id']= $_SESSION['username'];
                        $agentData['modified'] =date("Y-m-d H:i:s");
                        $agentData['supplement_cnt']=$agentTotal['supplement_cnt']+1;
                        $agentData['supplement_sum']=$agentTotal['supplement_sum']+$payment['trade_sum'];
                        $agentData['supplement_last_time']=date("Y-m-d H:i:s");
        
                        if($agentTotal['debt_balance']<=0){
                            $paymentData['account_balance_offset']=$payment['trade_sum'];
                            $paymentData['account_usage_balance_offset']=$payment['trade_sum'];
        
                            $agentData['balance']=$agentTotal['balance']+$payment['trade_sum'];
                            $agentData['usage_balance']=$agentTotal['usage_balance']+$payment['trade_sum'];
        
                            $paymentData['balance_now']=$agentData['balance'];
                            $paymentData['freeze_now']=$agentTotal['freezed_balance'];
                            $paymentData['usage_balance_now']=$agentData['usage_balance'];
                            $paymentData['debt_now']=$agentTotal['debt_balance'];
                        }else{
                            if($payment['trade_sum']>$agentTotal['debt_balance']){
                                $tradesum = $payment['trade_sum']-$agentTotal['debt_balance'];
                                $paymentData['account_balance_offset']=$tradesum;
                                $paymentData['account_usage_balance_offset']=$tradesum;
                                $paymentData['account_debt_balance_offset']=-$agentTotal['debt_balance'];
        
                                $agentData['balance']=$agentTotal['balance']+$tradesum;
                                $agentData['usage_balance']=$agentTotal['usage_balance']+$tradesum;
                                $agentData['debt_balance'] = 0;
        
                                $paymentData['balance_now']=$agentData['balance'];
                                $paymentData['freeze_now']=$agentTotal['freezed_balance'];
                                $paymentData['usage_balance_now']=$agentData['usage_balance'];
                                $paymentData['debt_now']=$agentData['debt_balance'];
                            }else{
                                $tradedebt = $agentTotal['debt_balance']-$payment['trade_sum'];
                                $paymentData['account_debt_balance_offset']=-$payment['trade_sum'];
                                $agentData['debt_balance'] = $tradedebt;
                                $paymentData['balance_now']=$agentTotal['balance'];
                                $paymentData['freeze_now']=$agentTotal['freezed_balance'];
                                $paymentData['usage_balance_now']=$agentTotal['usage_balance'];
                                $paymentData['debt_now']=$agentData['debt_balance'];
                            }
        
                        }
                        $agentAccountSercive->updateAccountAgentTradeLog($paymentData,$payment['id']);
                        $agentAccountSercive->updateAccountAgentTotal($agentData,$agentTotal['id']);
                        $logService->insertSystemLog('OS',$_SESSION['username'],1,$paymentData,$payment['id']);
                        $logService->insertSystemLog('OS',$_SESSION['username'],1,$agentData,$agentTotal['id']);        
                }
         
             }
                        
        }
        // insert payment_logs
        $logData = array();   
        $logData['user_id'] = $userId;
        $logData['response'] = json_encode(array($_POST,$verify_result));      
        $logData['type'] = "代理在线充值记录";
        $logData['modified'] = date ( "Y-m-d H:i:s" ); 
        $logData['created'] = date ( "Y-m-d H:i:s" );             
        $paymentService->insertPaymentLog($logData);         
        if($verify_result){  
            echo "success";
        }else{
            echo "fail";
        }
        exit();
    }
    
    public function supplyment(){
    	$tradeLogId = trim(HttpUtil::getPostString('id'));
    	$paymentService = new PaymentService();
    	$agentAccountSercive = new AgentAccountSercive();
    	$tradeLog = $agentAccountSercive->getTradeLogById($tradeLogId);
    	if(!empty($tradeLog)){
    		 $tradeSum = $tradeLog['trade_sum'];
    		 $sn = $tradeLog['sn'];
    		 if(!empty($tradeSum) && !empty($sn)){
                 $link = $paymentService->alipayPayment($tradeSum,$sn);
                 header("Location: " . $link);
                 exit();
    		 }
    	}
    	header("Location: http://".ConfigConstants::$domainPath."/trade/supplementlogs");
    }

    public function onlineorderpay(){
    	$id = HttpUtil::getGetString('orderId');
    	if(!empty($id)){
    		$paymentService = new PaymentService();
    		$orderService = new OrderService();
    		$id = base64_decode($id);
    		$orders = $orderService->getOrderInfoById($id);
            if(!empty($orders)){
            	$order = $orders[0];
            	$orderNo = $order['order_num'];
            	$orderTotal = $order['total'];
            	$discount = $order['discount_fee'];
            	$shipFee = $order['shipping_fee'];
//                $orderTotal = 0.02;
//                $discount = 0;
//                $shipFee = 0.01;
            	$status = $order['status'];
            	$logisticsType = $order['shipping_expect'];
            	if($status == 1){
            		$alipayLink = $paymentService->onlinePayment($orderNo,$orderTotal,$discount,$shipFee,$logisticsType);
            		header("Location: " . $alipayLink);
            	}
            }
    	}
    }

    public function onlinepayreturn(){
    	$paymentService = new PaymentService();
    	$verify_result = $paymentService->getPaymentResult();
    	if($verify_result){
    		if(trim($_GET['trade_status']) == 'WAIT_SELLER_SEND_GOODS' || trim($_GET['trade_status']) == "TRADE_FINISHED") {
    			 header("Location: /u/paymentinfo");
    		}
    	}
    }

    public function onlinepaynotify(){
        $paymentService = new PaymentService();
        
//        $logData['response'] = json_encode($_POST);
//        $paymentService->insertPaymentLog($logData); 
//             exit();        
        $orderService = new OrderService();
        $verify_result = $paymentService->getNotifyResult(); 
        $logData = array();    
        $userId = 0;
        if($verify_result){     	
             $orderNumber = trim($_POST['out_trade_no']);            
             $tradeStatus= trim($_POST['trade_status']);
             $refundStatus= trim($_POST['refund_status']); 
             $emailService = new EmailService();             
             if(!empty($orderNumber)){	
		             $order = $orderService->getOrderByOrderNo($orderNumber);  
		             $orderStatus = $order['status'];
		             $orderTotal = $order['total'];
		             $userId = $order['user_id'];
		             if($tradeStatus == "WAIT_SELLER_SEND_GOODS"){
		             	 if($orderStatus == 1){
		             	 	  $tempOrder = array();
		             	 	  $tempOrder['status'] = 3;
		             	 	  $orderService->updateOrderById($tempOrder,$order['id']);
		             	 }
		             }
		             if($tradeStatus == "WAIT_BUYER_CONFIRM_GOODS"){
		                 if($orderStatus == 3){
		                      $tempOrder = array();
		                      $tempOrder['status'] = 4;
		                      $orderService->updateOrderById($tempOrder,$order['id']);		                      
		                      $emailService->sendedGoogsEmailToUser($order['id']);
		                 }             	 
		             }
		             if($tradeStatus == "TRADE_FINISHED"){
		                 if($orderStatus == 4 || $orderStatus == 1){
		                      $tempOrder = array();
		                      $tempOrder['status'] = 5;
		                      $orderService->updateOrderById($tempOrder,$order['id']);
		                      $orderService->updateUserPoint($orderTotal,$userId,$orderNumber);
		                      $emailService->orderSuccessEmailToUser($order['id']);		                      
		                 }               	
		             }
		             if($tradeStatus == "TRADE_CLOSED" && $refundStatus == "REFUND_SUCCESS"){
		                   $tempOrder = array();
		                   $tempOrder['status'] = 7;
		                   $orderService->updateOrderById($tempOrder,$order['id']);       	
		             }

		             $logData['order_id'] = $order['id'];

		      
              }
        }
        $logData['user_id'] = $userId;
        $logData['response'] = json_encode(array($_POST,$verify_result));      
        $logData['type'] = "支付宝交易记录";
        $logData['modified'] = date ( "Y-m-d H:i:s" ); 
        $logData['created'] = date ( "Y-m-d H:i:s" );             
        $paymentService->insertPaymentLog($logData);
        if($verify_result){  
        	echo "success";
        }else{
        	echo "fail";
        }
        exit();
    }
    
    /**
     * 兑换礼品更新兑换积分
     */
    public function updatebuyerpoint(){
        $userId = AAService::getCustomer();
        $exchangeInfo = HttpUtil::getPostString("exchangeGoods");
        $exchangeInfoArray = explode("-", $exchangeInfo);
        $giftId = $exchangeInfoArray[0];
        $minAcPoints = $exchangeInfoArray[1];
        $exhaustPoints = $exchangeInfoArray[2];
        $customerService = new CustomerService();
        $userInfo = $customerService->getCustomerById($userId);
        $points_buyer = $userInfo[0]["points_buyer"];
        $points_buyer_total = $userInfo[0]["points_buyer_total"];
        if($points_buyer > 0 && $points_buyer >= $exhaustPoints){//用户符合兑换的晋级积分条件并且用户的兑换积分大于礼品的兑换积分
	        $new_points_buyer = $points_buyer - $exhaustPoints;
	        $customerService->updateBuyerPointByCid($userId, $new_points_buyer);
	        //添加日志文件信息
	        $applyGiftService = new ApplyGiftService();
	        $applyGiftService->saveApplyGiftLog(2, $giftId, $exhaustPoints, $points_buyer, $points_buyer_total);
        }
        
    	
    	header("Location: /userinfo/exchangegiftlist");
    }
    
    /**
     * 兑换抵用券更新兑换积分
     */
    public function exchangePromotion(){
        $userId = AAService::getCustomer();
        $exchangeInfo = HttpUtil::getPostString("exchangeCoupon");
        $exchangeInfoArray = explode("-", $exchangeInfo);
        $promotionId = $exchangeInfoArray[0];
        $minAcPoints = $exchangeInfoArray[1];
        $exhaustPoints = $exchangeInfoArray[2];
        $shortDescription = $exchangeInfoArray[3];
        $customerService = new CustomerService();
        $userInfo = $customerService->getCustomerById($userId);
        $points_buyer = $userInfo[0]["points_buyer"];
        $points_buyer_total = $userInfo[0]["points_buyer_total"];
        if($points_buyer > 0 && $points_buyer >= $exhaustPoints){//用户符合兑换的晋级积分条件并且用户的兑换积分大于抵用券的兑换积分
            $new_points_buyer = $points_buyer - $exhaustPoints;
            $customerService->updateBuyerPointByCid($userId, $new_points_buyer);
            //保存promotionCondition表信息
            $promotion_condition_type = 7;
            $condition_value = $userId;
            $code_value = Number::getGiftCouponCode();//调用方法生成随机的code
            $promotionCondition = array($promotionId, $promotion_condition_type, $condition_value, $code_value);
            $applyGiftService = new ApplyGiftService();
            $applyGiftService->savePromotionConditionInfo($promotionCondition);
            //添加日志文件信息
            $applyGiftService = new ApplyGiftService();
            $applyGiftService->saveApplyCouponLog(1, $exhaustPoints, $points_buyer, $points_buyer_total, $promotionId, $code_value);
            
            //给用户发信确认
            $email = $userInfo[0]["email"];
            $emailTitle = "阿基米米积分兑换优惠券通知";
            $emailBody = "您好，您使用{$exhaustPoints}积分，兑换了'{$shortDescription}'的优惠券<br/>优惠券折扣码是：{$code_value}";
            MailUtil::sendMail($email, $emailTitle, $emailBody);
            
        }
        
        header("Location: /userinfo/exchangegiftlist");
    	exit;
    }
    
    
    

}




